package com.simple.mq.sdk.producer;

import com.alibaba.fastjson.JSON;
import com.simple.mq.common.util.DateUtil;
import com.simple.mq.common.entity.po.SimpleMessage;
import com.simple.mq.sdk.client.SimpleMQClient;

import java.net.URI;
import java.util.Objects;

/**
 * 项目: simple-mq
 * <p>
 * 功能描述:
 *
 * @author: WuChengXing
 * @create: 2023-09-04 14:41
 **/
public class SimpleMqProducer {

    private final SimpleMQClient client;
    private String routingKey;

    public SimpleMqProducer(URI serverUri, String name) {
        this.client = new SimpleMQClient(serverUri, name, 1);
        try {
            client.connectBlocking();
        } catch (InterruptedException e) {
            //
        }
    }

    /**
     * 发送一条消息，包含routingKey
     *
     * @param message    消息，为json字符串格式
     * @param routingKey routingKey
     */
    public void send(Object message, String routingKey) {
        if (this.routingKey == null) {
            this.routingKey = routingKey;
        }
        SimpleMessage packaged = new SimpleMessage(1, message, routingKey, DateUtil.getLocalTime());
        client.send(JSON.toJSONString(packaged));
    }

    /**
     * 设置默认的routingKey
     *
     * @param key routingKey
     */
    public void setDefaultRoutingKey(String key) {
        this.routingKey = key;
    }

    public SimpleMQClient getClient() {
        return client;
    }
}
